package com.powerunion.datacollection.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.RoleDao;
import com.powerunion.datacollection.model.Role;
import com.powerunion.datacollection.model.jsonObject.RoleTreeNode;
import com.powerunion.util.DBUtils;
import com.powerunion.util.log.LogHelper;
import com.powerunion.util.query.jdbc.QueryParameters;

public class RoleDaoImpl extends JdbcBase implements RoleDao {
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			RoleDaoImpl.class);
	
	public String save(Role role) throws DaoException {
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "save");
		}

		String sql = "";
		String resultId = "";
		try {

			if (role.getId() == null || role.getId().equals("")) {//新增
				String id = String.valueOf(this.getSeq("dc_role"));
				role.setId(id);
				sql = this.sqlInsert();
			} else {//修改
				sql = this.sqlUpdate();
			}

			QueryParameters param = new QueryParameters();

			param.addParameter(role.getName(), Types.VARCHAR);
			param.addParameter(role.getDesc(), Types.VARCHAR);
			param.addParameter(new Integer(role.getRoleType()), Types.INTEGER);
			param.addParameter(role.getId(), Types.VARCHAR);

			this.execute(sql, param);
			resultId = role.getId();
		} catch (Exception e) {
			logger.error("save:" + Constants.SAVE + "role" + Constants.FAIL,e);
			throw new  DaoException("save throw error!");
		}
		if (logger.isDebugEnabled()) {
			logger.debug("save:" + Constants.SAVE + "role" + Constants.SUCCESS);
		}

		return resultId;

	}

	public Role findRoleByKey(String id) throws DaoException {
		String sql = this.sqlGetByKey();
		QueryParameters params = new QueryParameters();
		params.addParameter(id, Types.VARCHAR);
		Role role = null;
		try {
			role = (Role) this.findByKey(sql, params, "getRole");
		} catch (Exception e) {
			logger.error("findRoleByKey:" + Constants.SEARCH + "role"
					+ Constants.FAIL,e);
			throw new DaoException("search db record error!");
		}

		return role;
	}

	public final Role getRole(ResultSet rs) throws SQLException {
		Role role = new Role();

		role.setId(rs.getString("id"));
		role.setName(rs.getString("role_name"));
		role.setDesc(rs.getString("role_desc"));
		role.setRoleType(rs.getInt("role_type"));

		return role;
	}

	public boolean delete(String[] codes) throws DaoException {
		logger.debug(Constants.INTOMETHOD + "delete");
		boolean isSuccess = false;
		List batchParams = this.batchParams(codes, Types.VARCHAR);
		if (batchParams != null) {
			logger.error("delete:" + Constants.DELETE + "Roles"
					+ Constants.SUCCESS);
			try {
				this.executeBatch(this.sqlDelete(), batchParams);
				isSuccess = true;
			} catch (SQLException e) {
				logger.error("delete:" + Constants.DELETE + "roles" + Constants.FAIL,e);
				throw new DaoException("删除角色信息失败！");
			}
			
			return isSuccess;
		} else {
			return isSuccess;
		}
	}
	
	public List findRoles() throws DaoException {
		logger.debug(Constants.INTOMETHOD + "findRoles");
		QueryParameters params = new QueryParameters();
	
		String sql = this.sqlFindRoles();
		List list = null;
		try {
			list = this.list(sql, params, "getRole");
		} catch (Exception e) {
			logger.error("findRoles:" + Constants.SEARCH
					+ "roles" + Constants.FAIL,e);
			throw new DaoException("search db record error!");
		}
		logger.debug("findRoles" + Constants.SEARCH + "roles"
				+ Constants.SUCCESS);
		return list;
	}

	
	public JSONArray getUserTree(String paraSeq,int type) throws Exception {
		logger.info(Constants.INTOMETHOD + "getTree");
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List treeNodeArray = null;
		String sqlString = "";
		
		if(type == Constants.USER){
			sqlString = "select user_code,user_name from frameuser"; 
		}else if(type == Constants.DEPARTMENT){
			if (paraSeq == null || paraSeq.equals("null")) {
				sqlString = "select dept_code,dept_name from framedepartment where para_seq is null";
			} else {
				sqlString = "select dept_code,dept_name from framedepartment where para_seq=" + paraSeq;
			}
		}else if(type == Constants.WORKGROUP){
			sqlString = "select grop_code,grop_name from workgroup"; 
		}

		try {
			conn = this.getConnection();
			ps = conn.prepareStatement(sqlString);
			rs = ps.executeQuery();
			treeNodeArray = new ArrayList();

			while (rs.next()) {

					RoleTreeNode treeNode = new RoleTreeNode();
					treeNode.setId(rs.getString(1));
					treeNode.setText(rs.getString(2));
					treeNode.setExpandable(false);
					treeNode.setLeaf(true);
					if(type == Constants.DEPARTMENT){
						if (this.IsHasChildren(rs.getString(1),conn) > 0) { // 父节点
							treeNode.setLeaf(false);
						} 	
					}else if(type == Constants.USER){
						treeNode.setIconCls("collectionUserGroup");
					}else if(type == Constants.WORKGROUP){
						treeNode.setIconCls("workGroup");
					}

					treeNodeArray.add(treeNode);
				}
			// 得到JSON数组
			JSONArray jsonarr = JSONArray.fromObject(treeNodeArray);
			logger.debug("===============treeNodeArray.size():"
					+ treeNodeArray.size() + "========================");
			logger.debug("===============role user tree:" + jsonarr
					+ "========================");
			logger.debug(Constants.SEARCH + "role user tree" + Constants.SUCCESS);
			// 返回JSON数据
			return jsonarr;
		} catch (Exception e) {
			logger.error("getTree() of throws : ", e);
			throw new Exception(Constants.SEARCH + "role user tree"
					+ Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps, conn);
		}
	}
	
	public JSONArray getRoleTree() throws Exception {
		logger.info(Constants.INTOMETHOD + "getRoleTree");
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List treeNodeArray = null;
		StringBuffer sqlString = new StringBuffer();
		sqlString.append("select id,role_name,role_desc,role_type from dc_role");

		try {
			
			conn = this.getConnection();
			ps = conn.prepareStatement(sqlString.toString());
			rs = ps.executeQuery();
			treeNodeArray = new ArrayList();

			while (rs.next()) {

					RoleTreeNode treeNode = new RoleTreeNode();
					treeNode.setId(rs.getString("id"));
					treeNode.setText(rs.getString("role_name"));
					treeNode.setExpandable(false);
					treeNode.setDescription(rs.getString("role_desc"));
					String type = rs.getString("role_type");
					treeNode.setType(type);
					treeNode.setLeaf(true);
				
					switch(Integer.parseInt(type)){
					case Constants.WORKGROUP:
						treeNode.setIconCls("workGroup");
						break;
					default:
						treeNode.setIconCls("collectionUserGroup");
						break;
					}
					treeNodeArray.add(treeNode);
				}
			// 得到JSON数组
			JSONArray jsonarr = JSONArray.fromObject(treeNodeArray);
			logger.debug("===============treeNodeArray.size():"
					+ treeNodeArray.size() + "========================");
			logger.debug("===============category tree:" + jsonarr
					+ "========================");
			logger.debug(Constants.SEARCH + "role tree" + Constants.SUCCESS);
			// 返回JSON数据
			return jsonarr;
		} catch (Exception e) {
			logger.error("getRoleTree() of throws : ", e);
			throw new Exception(Constants.SEARCH + "role tree"
					+ Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps, conn);
		}
	}
	
	private int IsHasChildren(String parentId,Connection conn) throws Exception {

		String sql = "";
		int total = 0;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			sql = "select count(*) from framedepartment where para_seq=? ";
			ps = conn.prepareStatement(sql);
			ps.setString(1, parentId);

			rs = ps.executeQuery();

			if(rs.next()) {
				total = rs.getInt(1);
			}
			
		} catch (Exception e) {
			logger.error("IsHasChildren:" + Constants.SEARCH
					+ "departement children" + Constants.FAIL);
			logger.error("IsHasChildren() of throws : ", e);
			throw new Exception("IsHasChildren:" + Constants.SEARCH
					+ "departement children" + Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps);
		}

		return total;
	}
	
	protected String sqlInsert() {
		StringBuffer sql = new StringBuffer();
		sql.append("insert into dc_role(role_name,role_desc,role_type,id)").append(
				"values(?,?,?,?)");
		return sql.toString();
	}

	protected String sqlGetByKey() {
		StringBuffer sql = new StringBuffer();
		sql.append("select id,role_name,role_desc,role_type from dc_role where id = ?");

		return sql.toString();

	}
	
	protected String sqlFindRoles() {
		String sql = "select id,role_name,role_desc,role_type from dc_role ";
		return sql;
	}

	protected String sqlDelete() {
		StringBuffer sql = new StringBuffer();
		sql.append("delete from dc_role where id = ?");

		return sql.toString();
	}

	protected String sqlUpdate() {
		StringBuffer sql = new StringBuffer();
		sql.append("update dc_role set role_name=?,role_desc=?,role_type=? where id = ?");

		return sql.toString();
	}

}
